package com.springboot.project.service;


import com.springboot.project.common.ExcelResultEnum;
import com.springboot.project.entity.ExcelResult;
import com.springboot.project.entity.ExcelTemplate;
import com.springboot.project.mockData.ExcelTemplateMock;
import com.springboot.project.util.ExcelUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class ExcelService {


    public Object readExcelFile(MultipartFile file, Integer regionId, String val) {
        ExcelTemplate excelTemplate = getExcelTemplate(regionId);


        if (file != null) {
            // 获取文件
            Workbook wb = null;
            try {
                if (ExcelUtil.isExcel2007(file.getOriginalFilename())) {
                    wb = new XSSFWorkbook(file.getInputStream());
                } else if (ExcelUtil.isExcel2003(file.getOriginalFilename())) {
                    wb = new HSSFWorkbook(file.getInputStream());
                } else {
                    return "文件格式不支持";
                }
            } catch (IOException e) {
                return "获取文件失败";
            }

            // 解析文件 获取相应数据
            List<List<String>> lists;
            ExcelResult excelRelut = ExcelUtil.parseExcelByTemplate(wb, excelTemplate);
            if (Objects.equals(ExcelResultEnum.SUCCESS.getCodeStr(), excelRelut.getCode())) {
                lists = (List<List<String>>) excelRelut.getData();
            } else {
                return "解析Excel 文件失败";
            }

            // 根据 指标获取内容
            List<List<String>> resultList = getExcelDataByVal(lists,val);
            if (resultList.size() > 0) {
                return  resultList;
            } else {
                return "找不到对应数据";
            }

        } else {
            return "没有文件信息";
        }
    }

    public ExcelTemplate getExcelTemplate(Integer regionId) {

        List<ExcelTemplate> list = ExcelTemplateMock.getList();
        ExcelTemplate excelTemplate = null;
        for (ExcelTemplate temp : list) {
            if (Objects.equals(temp.getRegionId(), regionId)) {
                excelTemplate = temp;
            }
        }
        return excelTemplate;
    }

    public List<List<String>> getExcelDataByVal(List<List<String>> lists,String val){
        List<List<String>> list = new ArrayList<>();
        if (lists != null && lists.size() > 0) {
            for (List<String> beanList : lists) {
                for (String str : beanList) {
                    if (str.indexOf(val) != -1) {
                        list.add(beanList);
                        break;
                    }
                }
            }
        }
        return list;
    }

}
